package com.tudouji.framework.task;


import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.bill.domain.Sellform;
import com.tudouji.project.bill.domain.Sellitem;
import com.tudouji.project.bill.service.*;
import com.tudouji.project.customer.domain.Customer;
import com.tudouji.project.customer.mapper.CustomerMapper;
import com.tudouji.project.d3.domain.*;
import com.tudouji.project.d3.mapper.*;
import com.tudouji.project.d3.service.ID3ShopService;
import com.tudouji.project.d3.service.ILogisticRuleService;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.mapper.SalesspecificationMapper;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.mapper.SysUserMapper;
import com.tudouji.project.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.tudouji.framework.web.domain.AjaxResult.CODE_TAG;
import static com.tudouji.framework.web.domain.AjaxResult.MSG_TAG;

/**
 * D3批量生成销售订单
 */
@Slf4j
@Component("d3Task")
public class D3Task {

    @Autowired
    private ID3ShopService id3ShopService;
    @Autowired
    private D3ShopMapper d3ShopMapper;
    @Autowired
    private D3OrderMapper d3OrderMapper;
    @Autowired
    private D3ProToSpMapper d3ProToSpMapper;
    @Autowired
    private D3ProductMapper d3ProductMapper;
    @Autowired
    private D3ToSellformMapper d3ToSellformMapper;
    @Autowired
    private SalesspecificationMapper salesspecificationMapper;

    @Autowired
    private ISellformService sellformService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private D3Task d3Task;
    @Autowired
    private D3OrderTodoMapper d3OrderTodoMapper;
    @Autowired
    private ILogisticRuleService logisticRuleService;
    @Autowired
    private ISysConfigService sysConfigService;

    private static Map<String,Date> runState = new ConcurrentHashMap<>();

    List<D3Shop> d3Shops = new ArrayList<>();
//    Integer d3Proid;

    public void init() {
        d3Shops = id3ShopService.selectD3ShopList(new D3Shop());
    }

    public boolean canRun(String jobName){
        log.info("========检查"+jobName+"执行状态！========");
        if(runState.isEmpty()){
            runState.put(jobName,DateUtils.getNowDate());
            return true;
        }
        Date lastRunDate = runState.get(jobName);
        if(lastRunDate==null){
            runState.put(jobName,DateUtils.getNowDate());
            return true;
        }
        Date currentDate = DateUtils.getNowDate();
        long duration = currentDate.getTime() - lastRunDate.getTime();
        if(duration < 60000*5){
            log.info("========当前任务"+jobName +"正在运行，不能重复提交！");
            return false;
        }else{
            runState.put(jobName,DateUtils.getNowDate());
            return true;
        }
    }

    public void complete(String jobName){
        log.info("====当前任务"+jobName +"执行完成！======");
        runState.remove(jobName);
    }

    public void initProcess() {
        d3Shops = id3ShopService.selectD3ShopList(new D3Shop());
//        d3Proid = Integer.valueOf(this.sysConfigService.selectConfigByKey("d3_proid"));
//        //1: 一周一次，2: 一月一次，获取配置，计算开始截至日期，设置参数获取D3_ORDER
//        if (d3Proid == null) {
//            d3Proid = 1;
//        }
    }

    /**
     * 生成中间表
     */
    public void process() throws Exception {
        log.debug("===============D3生成中间表====================");
        initProcess();

        if (d3Shops.size() > 0) {
            for (D3Shop shop : d3Shops) {
                //4、系统遍历店铺表，一次处理一个店铺的数据，遍历的过程中检查当前店铺的相关配置是否具备处理的条件（ERP相关字段已设置），不具备条件则不处理当前店铺。
               /* if (0 == shop.getLogisticRule()) {
                    log.info("D3Task: shop.getLogisticRule(): " + shop.getLogisticRule());
                    continue;
                }*/
                if (null == shop.getDeptId()) {
                    log.info("D3Task: shop.getDeptId(): " + shop.getDeptId());
                    continue;
                }
                if (null == shop.getSubmitterId()) {
                    log.info("D3Task: shop.getSubmitterId(): " + shop.getSubmitterId());
                    continue;
                }
                if (null == shop.getCustomerId()) {
                    log.info("D3Task: shop.getCustomerId(): " + shop.getCustomerId());
                    continue;
                }
                //暂时不处理todo表，selectUnProcessD3Orders去掉了最大ID条件，已涵盖todo表中数据范围
//                    List<D3Order> orders = d3OrderTodoMapper.selectD3OrderByTodo(shop.getCode());
//                    createSellform(shop, orders, true);

                D3Order order = new D3Order();
                order.setPosCode(shop.getCode());
//                    order.setStatus("COMPLETE");
//                order.setStats(new String[]{"COMPLETE", "SHIPPED", "PART_SHIPPED", "BILL_SHIPPED", "BILL_COMPLETE"});
//                    order.setRefundStatus("NO_REFUND");
                order.setIsToSellform(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                order.setShippingTime(String.valueOf(sdf.parse(DateUtils.getDate()).getTime()));
                Date minDate = shop.getSyncDate();
                order.setShippingTimeSync(String.valueOf(minDate.getTime()));
                List<D3Order> orders = d3OrderMapper.selectUnProcessD3Orders(order);
                D3Shop shopUp = new D3Shop();
                shopUp.setId(shop.getId());
                shopUp.setRemark("clear");
                d3ShopMapper.updateD3Shop(shopUp);

                try {
                    d3Task.createSellform(shop, orders, false);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.debug(e.getMessage());
                    shopUp.setId(shop.getId());
                    shopUp.setRemark(e.getMessage());
                    d3ShopMapper.updateD3Shop(shopUp);
                }
            }
        }


        log.debug("===============D3生成中间表====================");
    }

    /**
     * 没有配置发货地址的订单，配置后，手工处理
     */
    public void d3OrderNoLogisticRule() {
        log.debug("===============D3电商订单发货地址处理====================");
        initProcess();

        if (d3Shops.size() > 0) {
            for (D3Shop shop : d3Shops) {
                //4、系统遍历店铺表，一次处理一个店铺的数据，遍历的过程中检查当前店铺的相关配置是否具备处理的条件（ERP相关字段已设置），不具备条件则不处理当前店铺。
                if (null == shop.getDeptId()) {
                    log.info("D3Task: shop.getDeptId(): " + shop.getDeptId());
                    continue;
                }
                if (null == shop.getSubmitterId()) {
                    log.info("D3Task: shop.getSubmitterId(): " + shop.getSubmitterId());
                    continue;
                }
                if (null == shop.getCustomerId()) {
                    log.info("D3Task: shop.getCustomerId(): " + shop.getCustomerId());
                    continue;
                }

                D3Order order = new D3Order();
                order.setPosCode(shop.getCode());
//                order.setIsToSellform(0);
                Date minDate = shop.getSyncDate();
                order.setShippingTime(String.valueOf(minDate.getTime()));
                String hour = sysConfigService.selectConfigByKey("GETWL_FOR_KUAINIAO_TASK_TIME");
                long miles = DateUtils.addHours(System.currentTimeMillis(), -Integer.valueOf(hour));

                order.setShippingTimeSync(String.valueOf(miles));
                List<D3Order> orders = d3OrderMapper.selectNoLogisticsSendFromD3Orders(order);
                for (int i = 0; i < orders.size(); i++) {
                    D3Order orderItem = orders.get(i);
                    if (StringUtils.isBlank(orderItem.getLogisticsOrderNo())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(orderItem.getLogisticsSendFrom())) {
                        log.error("logisticsSendFrom: " + orderItem.getLogisticsSendFrom());
                        continue;
                    }

                    try {
                        String sendFrom = logisticRuleService.getSendFromByRule(orderItem.getLogisticsOrderNo());
                        if (StringUtils.isEmpty(sendFrom)) {
                            //20231208 没有获取到地址直接return结束，修改为继续获取下一个订单地址
                            continue;
                        }
                        D3Order d3Order = new D3Order();
                        d3Order.setId(orderItem.getId());
                        d3Order.setLogisticsSendFrom(sendFrom);
                        d3OrderMapper.updateD3Order(d3Order);

                        //查询是否生成中间表，如果有中间表，将地址更新到中间表中
                        D3ToSellform d3ToSellform = new D3ToSellform();
                        d3ToSellform.setD3Orderid(orderItem.getId());
                        List<D3ToSellform> d3ToSellforms = d3ToSellformMapper.selectD3ToSellformList(d3ToSellform);
                        for (int j = 0; j < d3ToSellforms.size(); j++) {
                            D3ToSellform item = d3ToSellforms.get(j);
                            D3ToSellform toBeUpdated = new D3ToSellform();
                            toBeUpdated.setId(item.getId());
                            toBeUpdated.setLogisticsSendFrom(sendFrom);
                            d3ToSellformMapper.updateD3ToSellform(toBeUpdated);
                        }
                        if (i != 0 && i % 8 == 0) {
                            Thread.sleep(5000L);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                D3Shop shopUp = new D3Shop();
                shopUp.setId(shop.getId());
                shopUp.setRemark("clear");
                d3ShopMapper.updateD3Shop(shopUp);
            }
        }


        log.debug("===============D3电商订单发货地址处理====================");
    }

    /**负责生成电商订单中间表
     * @param shop
     * @param orders
     * @param todo   ture:来自待处理表中，插入中间表后需要删除待处理数据
     */
    @Transactional
    public void createSellform(D3Shop shop, List<D3Order> orders, boolean todo) {
        if (orders.size() == 0) {
            log.info("店铺编号：" + shop.getCode() + " 没有已完成的订单");
            throw new CustomException("店铺编号：" + shop.getCode() + " 没有已完成的订单");
        } else {
            for (D3Order orderItem : orders) {

                List<D3OrderItem> lines = orderItem.getLines();
                if (lines.size() == 0) {
                    log.info("订单编号：" + orderItem.getRefOid() + " 没有已完成的明细");
//                    continue;
                    throw new CustomException("订单编号：" + orderItem.getRefOid() + " 没有已完成的明细");
                }
                //如果d3_order已生成中间表，直接删除掉todo中的待处理数据
                if (todo && orderItem.getIsToSellform() == 1) {
                    deleteD3Todo(true, lines.get(0));
//                    continue;
                    throw new CustomException("");
                }
                d3ItemToSellform(orderItem, lines, shop.getId(), todo);
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void d3ItemToSellform(D3Order order, List<D3OrderItem> lines, Long shopId, boolean todo) {
        for (D3OrderItem item : lines) {
            D3Product d3Product = d3ProductMapper.selectD3ProductBySku(item.getRefSkuId());
            if (StringUtils.equalsIgnoreCase(d3Product.getMatchstatus(), "0")){
                updateD3orderIsto(order.getId(), 2);
                return;
            }
            List<D3ProToSp> d3ProToSpList = prepareD3orderSellform(order, shopId, item);

            insertD3OrderSellform(order, shopId, item, d3ProToSpList);

            deleteD3Todo(todo, item);
        }
        updateD3orderIsto(order.getId(), 1);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void deleteD3Todo(boolean todo, D3OrderItem item) {
        if (todo) {
            d3OrderTodoMapper.deleteD3OrderTodoByD3OrderId(item.getD3OrderId());
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void updateD3orderIsto(Long d3OrderId, Integer isToSellform) {
        D3Order d3Order = new D3Order();
        d3Order.setId(d3OrderId);
        d3Order.setIsToSellform(isToSellform);
        d3OrderMapper.updateD3Order(d3Order);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public List<D3ProToSp> prepareD3orderSellform(D3Order order, Long shopId, D3OrderItem item) {
        D3ProToSp d3ProToSp = new D3ProToSp();
        d3ProToSp.setShopId(shopId);
        d3ProToSp.setRefspuid(item.getRefSpuId());
        d3ProToSp.setRefskuid(item.getRefSkuId());
        List<D3ProToSp> d3ProToSpList = d3ProToSpMapper.selectD3ProToSpList(d3ProToSp);
        if (d3ProToSpList.size() == 0) {
            log.info("商品对应关系表没有配置Sku: " + item.getRefSkuId());
            D3Order orderTo = new D3Order();
            orderTo.setId(order.getId());
            order.setRemark("商品没有配置对应关系");
            d3OrderMapper.updateD3Order(order);
            throw new CustomException("商品对应关系表没有配置：" + item.getRefSkuId());
        }
        d3ProToSp.setNum(item.getNum());
        d3ProToSp.setPrice(new BigDecimal(item.getSingleFee()));
        d3ProToSpList = d3ProToSpMapper.transferToSellform(d3ProToSp);
        return d3ProToSpList;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void insertD3OrderSellform(D3Order order, Long shopId, D3OrderItem item, List<D3ProToSp> d3ProToSpList) {
        D3ToSellform toSellform = new D3ToSellform();
        toSellform.setShopId(shopId);
        toSellform.setD3Orderid(item.getD3OrderId());
        toSellform.setD3OrderItemid(item.getId());
        toSellform.setStatus(1);
        toSellform.setRefOid(order.getRefOid());
        toSellform.setFinishTime(order.getFinishTime());
        toSellform.setShippingTime(order.getShippingTime());
//            d3ToSellformMapper.deleteD3ToSellformByD3(toSellform);

        toSellform.setD3OiRefskuid(item.getRefSkuId());
        toSellform.setD3OiTitle(item.getTitle());
        toSellform.setD3OiStandards(item.getStandards());
        toSellform.setCreateTime(DateUtils.getNowDate());
        //2023-10-23中间表添加发货地址
        if (StringUtils.isNotEmpty(order.getLogisticsOrderNo()) && StringUtils.isEmpty(order.getLogisticsSendFrom())) {
            return;
        }
        toSellform.setLogisticsSendFrom(order.getLogisticsSendFrom());

        for (D3ProToSp toSellformItem : d3ProToSpList) {
            toSellform.setD3PosCode(toSellformItem.getD3PosCode());
            toSellform.setSpId(toSellformItem.getSpId());
            toSellform.setSpName(toSellformItem.getSpName());

            //20231113 根据spguid，获取该物料所属的产品大类，写入中间表
            List<D3ToSellform> productTypes = d3ToSellformMapper.selectProductType(toSellform);
            if(productTypes.size()!=1){
                throw new CustomException("物料所属大类配置不正确，请检查物料配置");
            }
            toSellform.setProductType(productTypes.get(0).getProductType());

            toSellform.setNum(toSellformItem.getNum());
            toSellform.setPrice(toSellformItem.getPrice());
            d3ToSellformMapper.insertD3ToSellform(toSellform);
        }
    }

    /**
     * 生成ERP订单
     */
    public void start() throws Exception {
        log.debug("===============D3生成销售订单开始====================");
        String jobName = "CreateSellForm";
        //不能并发，所以需要判断当前批量业务的状态
        if(!canRun(jobName)){
            return;
        }
        init();

        //由获取当前日期的昨天，修改为获取当前日期的前天数据，为了满足写入地址条件
        Date loadingTime = DateUtils.addDay(DateUtils.getNowDay(), -2);
        loadingTime = DateUtils.getLastDayOfDate(loadingTime);

        //金蝶结账日
        String overDate = sysConfigService.selectConfigByKey("over_date");

        if (d3Shops.size() > 0) {
            for (D3Shop shop : d3Shops) {
                //4、系统遍历店铺表，一次处理一个店铺的数据，遍历的过程中检查当前店铺的相关配置是否具备处理的条件（ERP相关字段已设置），不具备条件则不处理当前店铺。
                String syncRate = shop.getSyncRate();
                /*if (0 == shop.getLogisticRule()) {
                    log.info(shop.getLogisticRule() + "店铺发货地址配置为0");
                    continue;
                }*/

                if (StringUtils.isBlank(syncRate)) {
                    log.info(shop.getName() + " 店铺corn表达式为空！");
                    continue;
                }
                if (syncRate.startsWith("NO")) {
                    log.info(shop.getName() + " 店铺不生成销售订单！");
                    continue;
                }

                CronExpression expression = new CronExpression(syncRate);
                if (!expression.isSatisfiedBy(DateUtils.getNowDay())&&
                   DateUtils.getDayOfMonth()!=DateUtils.getEndDayOfMonth()) {
                    log.info(shop.getName() + " 店铺corn表达式不满足！");
                    continue;
                }

                if (null == shop.getDeptId()) {
                    log.info("D3Task: shop.getDeptId(): " + shop.getDeptId());
                    continue;
                }

                if (null == shop.getDeptId()) {
                    log.info("D3Task: shop.getDeptId(): " + shop.getDeptId());
                    continue;
                }
                if (null == shop.getSubmitterId()) {
                    log.info("D3Task: shop.getSubmitterId(): " + shop.getSubmitterId());
                    continue;
                }
                if (null == shop.getCustomerId()) {
                    log.info("D3Task: shop.getCustomerId(): " + shop.getCustomerId());
                    continue;
                }
                if (null == shop.getSyncDate()) {
                    log.info(shop.getName() + " 店铺没有设置同步日期！");
                    continue;
                }



                //202311130如果当前日大于金蝶系统结账日overDate,则不分月同步订单
                Date syncDate = shop.getSyncDate();
                loadingTime = MeituanDataProcessUtil.getLoadingTime(syncDate,loadingTime,1,Integer.parseInt(overDate));
//                if (DateUtils.getNowDate().getDate() <= Integer.valueOf(overDate).intValue()){//
//                    loadingTime = getLoadingTime(syncDate, loadingTime);
//                }

                D3Order d3Order = new D3Order();
                d3Order.setPosCode(shop.getCode());
                d3Order.setIsToSellform(0);
                d3Order.setShippingTime(String.valueOf(loadingTime.getTime()));
                d3Order.setShippingTimeSync(String.valueOf(syncDate.getTime()));
                List<D3Order> d3Orders = d3OrderMapper.selectD3OrderList(d3Order);
                if (logisticsSendFromHave(shop, d3Orders)) continue;
                //5、系统首先获取到当前店铺已生成ERP订单的最大电商销售订单表（D3_order）的id（从关联关系表？或者从D3_order表查询）
                // ，遍历当前店铺的大于该id的电商销售订单表数据（状态正常的）。
//                    D3Order order = new D3Order();
//                    order.setPosCode(shop.getCode());
//                    order.setStatus("COMPLETE");
//                    order.setRefundStatus("NO_REFUND");
//                    long startId = id3OrderService.selectSFCreateNotedForMinId(order);


                D3ToSellform d3ToSellform = new D3ToSellform();
                d3ToSellform.setStatus(1);
                d3ToSellform.setShopId(shop.getId());
                d3ToSellform.setShippingTime(String.valueOf(loadingTime.getTime()));

                d3ToSellform.setShippingTimeSync(String.valueOf(syncDate.getTime()));
                List<D3ToSellform> orderItemsGroupBy = d3ToSellformMapper.selectD3ToSellformListGroupBy(d3ToSellform);
                if (orderItemsGroupBy.size() == 0) {
                    continue;
                }

                for (int i = 0; i < orderItemsGroupBy.size(); i++) {
                    d3ToSellform.setLogisticsSendFrom(orderItemsGroupBy.get(i).getLogisticsSendFrom());
//                    d3ToSellform.setType(orderItemsGroupBy.get(i).getType());
                    d3ToSellform.setProductType(orderItemsGroupBy.get(i).getProductType());
                    List<D3ToSellform> orderItems = d3ToSellformMapper.selectD3ToSellformListGroupByItem(d3ToSellform);
                    if (orderItems.size() == 0) {
                        log.info(shop.getName() + " 没有待处理的中间数据！");
                        continue;
                    }
                    List<D3ToSellform> orderItemsSum = d3ToSellformMapper.preparedForSellItems(d3ToSellform);
                    List<D3Order> orders = d3ToSellformMapper.preparedForD3Orders(d3ToSellform);
                    BigDecimal sellformAmount = d3ToSellformMapper.preparedForSellformAmount(d3ToSellform);

//                    order.setId(startId);
//                    List<D3OrderItem> orderItems = id3OrderItemService.selectSFNotCreateOrderItems(order);
//                    BigDecimal sellformAmount = d3OrderMapper.selectReceivedPaymentSum(order);
//                    List<D3Order> orders = d3OrderMapper.selectSFNotCreateOrders(order);
                    try {
                        d3Task.createSellform(shop, orderItemsSum, sellformAmount, orders, orderItems, d3ToSellform.getLogisticsSendFrom(),syncDate, loadingTime);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.debug(e.getMessage());
                    }
                }
            }

        }

        complete(jobName);
        log.debug("===============D3生成销售订单结束====================");
    }

    /**
     * D3推送时，如果获取到的没有生成中间表的订单，都没有地址，则表示被拦截，继续生成推送数据
     *          如果有一个订单有地址，说明还有未处理中间表的订单，跳过，需要先处理中间表
     * @param shop
     * @param d3Orders
     * @return
     */
    private boolean logisticsSendFromHave(D3Shop shop, List<D3Order> d3Orders) {
        if (d3Orders.size() > 0) {
            for (int i = 0; i < d3Orders.size(); i++) {
                D3Order item = d3Orders.get(i);
                if (StringUtils.isNotBlank(item.getLogisticsSendFrom())){
                    D3Shop shopUp = new D3Shop();
                    shopUp.setId(shop.getId());
                    shopUp.setRemark(item.getRefOid() + "没有生成中间表！");
                    d3ShopMapper.updateD3Shop(shopUp);
                    return true;
                }
            }
            log.info(DateUtils.getNowDate()+" 共有"+d3Orders.size()+"订单无发货地址，跳过");
            D3Shop shopUp = new D3Shop();
            shopUp.setId(shop.getId());
            shopUp.setRemark("共有"+d3Orders.size()+"张电商订单无发货地址，不生成ERP订单");
            d3ShopMapper.updateD3Shop(shopUp);
        }
        return false;
    }


    /**
     * 创建销售订单
     * @param shop
     * @param orderItemsSum
     * @param receivedPaymentSum
     * @param orders
     * @param orderItems
     * @param logisticSendFrom
     */
    @Transactional
    public void createSellform(D3Shop shop, List<D3ToSellform> orderItemsSum, BigDecimal receivedPaymentSum
            , List<D3Order> orders, List<D3ToSellform> orderItems, String logisticSendFrom, Date sycDate, Date loadingDate) {
        Long deptId = shop.getDeptId();
        Long customerId = shop.getCustomerId();
        Long submitterId = shop.getSubmitterId();
        Customer customer = customerMapper.selectCustomerByNewId(customerId);
        SysUser sysUser = sysUserMapper.selectUserById(submitterId);
        Sellform sellform = setSellform(receivedPaymentSum, customer);
        List<Sellitem> items = setSellitems(orderItemsSum);
        sellform.setItems(items);
        BigDecimal weight = BigDecimal.ZERO;
        for (Sellitem item : items) {
            weight = weight.add(item.getWeight());
        }
        //2023-04-26添加备注信息：电商订单生成包含多少个店铺订单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String remark = "系统自动生成从" + sdf.format(sycDate) + "到" + sdf.format(loadingDate) + "，" + shop.getName() + "平台订单数: " + orders.size()
                + "，ERP平台单品数: " + weight.intValueExact();
        if (StringUtils.isNotBlank(logisticSendFrom)) {
            remark += ",发货地址：" + logisticSendFrom;
        }
        sellform.setRemarks(remark);
        sellform.setPlantformLoadDate(loadingDate);

        AjaxResult result = sellformService.saveOrUpdate(sellform, deptId, null, null, "系统根据电商平台订单自动发起", sysUser);
        if ((result.get(CODE_TAG)).equals(200)) {
            Sellform sf = sellformService.selectSellformByGuid((String) result.get(MSG_TAG));
            for (D3Order order : orders) {
                order.setSfId(sf.getId());
                order.setSfCode(sf.getSellcode());
                d3OrderMapper.updateD3Order(order);
            }
            for (D3ToSellform order : orderItems) {
                order.setStatus(5);
                order.setSellformId(sf.getId());
                order.setSellformCode(sf.getSellcode());
                d3ToSellformMapper.updateD3ToSellform(order);
            }
            //2023-10-24 更新店铺同步时间
//            D3ToSellform d3ToSf = new D3ToSellform();
//            d3ToSf.setShopId(shop.getId());
//            String date = d3ToSellformMapper.getMaxShippingTime(d3ToSf);
//            shop.setSyncDate(new Date(Long.valueOf(date)));
            D3Shop d3Shop = new D3Shop();
            d3Shop.setId(shop.getId());
            d3Shop.setSyncDate(DateUtils.addSeconds(loadingDate, 1));
            d3ShopMapper.updateD3Shop(d3Shop);
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    private static Sellform setSellform(BigDecimal receivedPaymentSum, Customer customer) {
        Sellform sellform = new Sellform();
        sellform.setFlowtempguid("34");
        sellform.setCustomerguid(customer.getGuid());
        sellform.setQuitsrtype(2);
        sellform.setFlag(4);
        sellform.setPaytype(3);
        sellform.setDeliverytype(2);
        sellform.setAmount(receivedPaymentSum);
        sellform.setFinalamount(receivedPaymentSum);
        sellform.setSettletype(1);
        sellform.setSettledays(1);
        sellform.setType(1);
        sellform.setPartitionflag(1);
        sellform.setSenddate(DateUtils.getDate());
        sellform.setArrivedate(DateUtils.getDate());
        sellform.setAutoType(1);
        sellform.setCurrency(1);
        sellform.setSettlebilling(0);
        return sellform;
    }


    private List<Sellitem> setSellitems(List<D3ToSellform> orders) {
        List<Sellitem> items = new ArrayList<>();
        for (int i = 0; i < orders.size(); i++) {
            D3ToSellform orderItem = orders.get(i);
            Sellitem item = new Sellitem();
            if (null == orderItem.getSpId()) {
                throw new CustomException("setSellitems: sku: " + orderItem.getD3OiRefskuid() + " is not seted spId!");
            }
            Salesspecification salesspecification = salesspecificationMapper.selectSalesspecificationByAutoId(orderItem.getSpId());
            item.setProductguid(salesspecification.getProductguid());
            item.setProductname(salesspecification.getProductname());
            item.setSpguid(salesspecification.getGuid());
            item.setSpname(salesspecification.getName());
            item.setWeight(BigDecimal.valueOf(orderItem.getNum()));
            item.setLoadweight(BigDecimal.valueOf(orderItem.getNum()));
            item.setSettleweight(BigDecimal.valueOf(orderItem.getNum()));
            item.setSettletype(1);
            item.setPrice(orderItem.getPrice());
            item.setSettleamount(orderItem.getAmount());
            item.setFlag(salesspecification.getFlag());
            items.add(item);
        }
        return items;
    }
}
